package com.lyn.serialPort;

import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class SerialPortManager extends SerialPort {
    private static final String TAG = SerialPortManager.class.getSimpleName();
    private FileInputStream inputStream;
    private FileOutputStream outputStream;
    private FileDescriptor descriptor;
    private boolean isOpen = false;
    private SerialPortFinder serialPortFinder;


    public boolean openSerialPort(String name, int baudRate) {
        if (serialPortFinder==null){
            serialPortFinder=new SerialPortFinder();
        }
        Device device = serialPortFinder.getDevice(name);
        if (device==null){
            return false;
        }
        File file = device.getFile();
        if (!file.canRead() || !file.canWrite()) {
            boolean chmod777 = this.chmod777(file);
            if (!chmod777) {
                Log.i(TAG, "openSerialPort: 没有读写权限");
                return false;
            }
        }
        try {
            this.descriptor = this.open(file.getAbsolutePath(), baudRate, 0);
            this.inputStream = new FileInputStream(this.descriptor);
            this.outputStream = new FileOutputStream(this.descriptor);
            Log.i(TAG, "openSerialPort: 串口已经打开 " + this.descriptor);
            isOpen = true;
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            return false;
        }
    }

    public boolean sendData(byte[] data) {
        if (isOpen && outputStream != null) {
            try {
                outputStream.write(data);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public void closeSerialPort() {
        try {
            close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public FileInputStream getInputStream() {
        return inputStream;
    }

    public FileOutputStream getOutputStream() {
        return outputStream;
    }

    public FileDescriptor getDescriptor() {
        return descriptor;
    }

    public boolean isOpen() {
        return isOpen;
    }

}
